package hn.sigit.view.docviewer;

import hn.sigit.logic.bpm.DocumentViewer;
import hn.sigit.util.AppOptions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.servlet.ContextualHttpServletRequest;
import org.jboss.seam.web.AbstractResource;

@Scope(ScopeType.APPLICATION)
@Name("documentViewerResource")
@BypassInterceptors
public class DocumentViewerResource extends AbstractResource {

	@Override
	public String getResourcePath() {
		return "/documentviewer";
	}

	@Override
	public void getResource(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException, IOException {
		new ContextualHttpServletRequest(request) {
            @Override
            public void process() throws IOException {
                doWork(request, response);
            }
        }.run();
	}
	
	private void doWork(HttpServletRequest request, HttpServletResponse response) {
		final int BSIZE = 4196;
        DocumentViewer document = (DocumentViewer)Component.getInstance("documentViewer");
    	AppOptions appOptions = (AppOptions)Component.getInstance("appOptions");

		try {
			ServletOutputStream outputStream = response.getOutputStream();
			response.setContentType(document.getAppropriateMIME());
			if (document.isForceDownload())
				response.setHeader("Content-Disposition", "attachment;filename=\"" + document.getDocumentPath() + "\"");
			File fileToDownload = new File(document.getDocumentPath());
			FileInputStream fis = new FileInputStream(fileToDownload);
			byte[] bytes = new byte[BSIZE];
			int nread;
			
			while ((nread = fis.read(bytes, 0, bytes.length)) != -1)
				outputStream.write(bytes, 0, nread);
			
			outputStream.flush();
			outputStream.close();
		}
		catch (IOException ioe) {
			System.err.println(ioe.getMessage());
		}
    }
	
	private File pathToFile(String dir, String fname) throws FileNotFoundException {
		String fullPath = dir + "/" + fname;
		
		fullPath = fullPath.replaceAll("//", "/");
		
		File f = new File(fullPath);
		if (!f.exists())
			throw new FileNotFoundException("File not found: " + f.getName());
		return f;
	}
}
